/**
 * 伯乐智能HR - Living Workspace 主应用
 * 基于原生JavaScript + 类架构的对话驱动动态工作台
 * 架构风格与JH子系统保持一致
 */

class LivingWorkspace {
    constructor() {
        // 动态获取当前页面的端口，避免硬编码
        this.apiBaseUrl = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/api`;
        console.log('🔧 API基础URL:', this.apiBaseUrl);
        this.candidateList = [];
        this.selectedCandidate = null;
        this.sending = false;
        this.isDark = false;
        
        // WebSocket相关
        this.wsUrl = `ws://${window.location.hostname}:${window.location.port}/ws/status`;
        this.websocket = null;
        this.isReconnecting = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        
        // 时间线相关
        this.activeTimeline = null;
        this.timelineStages = [];
        this.currentStageIndex = 0;
        
        this.init();
    }
    
    async init() {
        console.log('初始化伯乐智能HR Living Workspace...');
        
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initializeApp());
        } else {
            this.initializeApp();
        }
    }
    
    initializeApp() {
        this.initializeDOM();
        this.bindEvents();
        this.initializeTheme();
        this.initializeWebSocket();
        this.checkSystemStatus();
        this.loadAllCandidates(); // 默认加载所有候选人
        
        console.log('✅ Living Workspace 初始化完成');
    }
    
    initializeDOM() {
        this.elements = {
            chatHistory: document.getElementById('chatHistory'),
            chatInput: document.getElementById('chatInput'),
            sendBtn: document.getElementById('sendBtn'),
            candidateList: document.getElementById('candidateList'),
            emptyState: document.getElementById('emptyState'),
            welcomeMessage: document.getElementById('welcomeMessage'),
            themeToggle: document.getElementById('themeToggle'),
            quickSuggestions: document.getElementById('quickSuggestions'),
            statusFilter: document.getElementById('statusFilter'),
            sortSelect: document.getElementById('sortSelect'),
            showAllCandidatesBtn: document.getElementById('showAllCandidatesBtn'),
            
            // 时间线相关元素
            agentStatusTimeline: document.getElementById('agentStatusTimeline'),
            timelineContent: document.getElementById('timelineContent'),
            timelineProgress: document.getElementById('timelineProgress'),
            closeTimelineBtn: document.getElementById('closeTimelineBtn')
        };
    }
    
    bindEvents() {
        if (this.elements.sendBtn) {
            this.elements.sendBtn.addEventListener('click', () => this.sendMessage());
        }
        
        if (this.elements.chatInput) {
            this.elements.chatInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendMessage();
                }
            });
        }
        
        if (this.elements.themeToggle) {
            this.elements.themeToggle.addEventListener('click', () => this.toggleTheme());
        }
        
        if (this.elements.quickSuggestions) {
            this.elements.quickSuggestions.addEventListener('click', (e) => {
                if (e.target.classList.contains('suggestion-btn')) {
                    this.sendQuickSuggestion(e.target.textContent);
                }
            });
        }
        
        // Tab切换事件
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab));
        });
        
        // 时间线关闭按钮事件
        if (this.elements.closeTimelineBtn) {
            this.elements.closeTimelineBtn.addEventListener('click', () => this.hideTimeline());
        }
        
        // 候选人筛选事件
        if (this.elements.statusFilter) {
            this.elements.statusFilter.addEventListener('change', () => this.applyFilters());
        }
        
        if (this.elements.sortSelect) {
            this.elements.sortSelect.addEventListener('change', () => this.applyFilters());
        }
        
        // 查看所有候选人按钮
        if (this.elements.showAllCandidatesBtn) {
            this.elements.showAllCandidatesBtn.addEventListener('click', () => {
                console.log('🔘 点击查看所有候选人按钮');
                this.showAllCandidates();
            });
            console.log('✅ 查看所有候选人按钮事件已绑定');
        } else {
            console.error('❌ 未找到查看所有候选人按钮元素');
        }
    }
    
    initializeTheme() {
        const savedTheme = localStorage.getItem('livingWorkspace_theme');
        if (savedTheme === 'dark') {
            this.isDark = true;
            document.documentElement.setAttribute('data-theme', 'dark');
            if (this.elements.themeToggle) {
                this.elements.themeToggle.querySelector('i').className = 'fas fa-sun';
            }
        }
    }
    
    async checkSystemStatus() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/hr/test-frontend`);
            const data = await response.json();
            
            if (data.success) {
                console.log('✅ 系统状态正常');
                
                // 加载岗位信息
                await this.loadCurrentJob();
            }
        } catch (error) {
            console.warn('系统状态检查失败:', error);
        }
    }
    
    // 加载当前岗位信息
    async loadCurrentJob() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/hr/current-job`);
            const data = await response.json();
            
            if (data.success && data.job) {
                this.displayJobInfo(data.job);
            } else {
                console.warn('获取岗位信息失败:', data.error);
            }
        } catch (error) {
            console.error('加载岗位信息失败:', error);
        }
    }
    
    // 显示岗位信息
    displayJobInfo(job) {
        const jobCard = document.getElementById('jobRequirementCard');
        if (!jobCard) return;
        
        // 更新岗位基本信息
        const titleEl = document.getElementById('jobTitle');
        const companyEl = document.getElementById('jobCompany');
        const statusEl = document.getElementById('jobStatus');
        const locationEl = document.getElementById('jobLocation');
        const salaryEl = document.getElementById('jobSalary');
        const experienceEl = document.getElementById('jobExperience');
        const requiredSkillsEl = document.getElementById('requiredSkills');
        
        if (titleEl) titleEl.textContent = job.title || '岗位加载中...';
        if (companyEl) companyEl.textContent = job.company_name || '公司名称';
        if (statusEl) statusEl.textContent = job.status || '招聘中';
        if (locationEl) locationEl.textContent = job.location || '工作地点';
        if (salaryEl) salaryEl.textContent = job.job_requirements?.salary_range || '面议';
        if (experienceEl) experienceEl.textContent = `${job.min_experience_years || 0}年经验`;
        
        // 更新技能要求
        if (requiredSkillsEl && job.required_skills) {
            requiredSkillsEl.innerHTML = '';
            if (job.required_skills.length > 0) {
                job.required_skills.forEach(skill => {
                    const skillTag = document.createElement('span');
                    skillTag.className = 'skill-tag';
                    skillTag.textContent = skill;
                    requiredSkillsEl.appendChild(skillTag);
                });
            } else {
                requiredSkillsEl.innerHTML = '<span class="skill-tag">暂无特定要求</span>';
            }
        }
        
        // 更新招聘统计数据
        if (job.recruitment_stats) {
            const stats = job.recruitment_stats;
            const totalResumesEl = document.getElementById('totalResumes');
            const qualifiedCandidatesEl = document.getElementById('qualifiedCandidates');
            const pythonSpecialistsEl = document.getElementById('pythonSpecialists');
            
            if (totalResumesEl) totalResumesEl.textContent = stats.total_resumes || '0';
            if (qualifiedCandidatesEl) qualifiedCandidatesEl.textContent = stats.qualified_candidates || '0';
            if (pythonSpecialistsEl) pythonSpecialistsEl.textContent = stats.python_specialists || '0';
        }
        
        // 显示岗位卡片
        jobCard.style.display = 'block';
        
        console.log('✅ 岗位信息已显示:', job.title);
    }
    
    async sendMessage() {
        const message = this.elements.chatInput?.value?.trim();
        if (!message || this.sending) return;
        
        this.sending = true;
        this.updateSendButton(true);
        
        // 显示时间线
        if (this.showTimeline) {
            this.showTimeline();
        }
        
        // 添加用户消息
        console.log('🔵 创建用户消息:', message);
        const userMessageId = this.addMessage('user', message);
        console.log('🔵 用户消息ID:', userMessageId);
        this.elements.chatInput.value = '';
        
        // 隐藏欢迎消息
        if (this.elements.welcomeMessage) {
            this.elements.welcomeMessage.style.display = 'none';
        }
        
        // 添加AI思考消息
        console.log('🤖 创建AI占位符消息');
        const aiMessageId = this.addMessage('ai', '', true);
        console.log('🤖 AI消息ID:', aiMessageId);
        console.log('🔍 消息ID对比:', { userMessageId, aiMessageId });

        // **根本性修复**：确保只使用 async/await 结合 try/catch 的模式处理请求
        // 移除所有遗留的 .then/.catch 链条，避免逻辑混乱
        try {
            console.log('🔍 发送命令:', message);
            const response = await fetch(`${this.apiBaseUrl}/chat`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message })
            });

            if (!response.ok) {
                const errorText = await response.text().catch(() => '无法读取响应体');
                console.error('❌ HTTP请求失败:', { status: response.status, statusText: response.statusText, body: errorText });
                // 确保更新AI占位符
                this.updateMessage(aiMessageId, `请求失败: ${response.statusText} (状态码: ${response.status})`);
                return; // 提前退出
            }

            const data = await response.json();
            console.log('✅ API请求成功, 响应数据:', data);

            if (data.success) {
                // 确保更新AI占位符
                console.log('✅ 成功响应，更新AI消息ID:', aiMessageId);
                this.updateMessage(aiMessageId, data.message || '处理完成');
                
                // 处理候选人数据
                if (data.analyzed_candidates && data.analyzed_candidates.length > 0) {
                    this.updateCandidateList(data.analyzed_candidates);
                }
                
                // 处理UI指令
                if (data.ui_commands && data.ui_commands.length > 0) {
                    this.processUICommands(data.ui_commands);
                }
                
                // 处理面试题
                if (data.interview_questions) {
                    this.showInterviewQuestions(data.interview_questions);
                }
                
                // **新增：检测并更新笔记**
                this.checkAndUpdateNotes(message, data);
            } else {
                 // 确保更新AI占位符
                console.log('❌ 错误响应，更新AI消息ID:', aiMessageId);
                this.updateMessage(aiMessageId, `抱歉，处理时发生错误：${data.error || '未知服务器错误'}`);
            }

        } catch (error) {
            console.error('❌ API请求或网络连接失败:', error);
            // 最终防线：确保更新AI占位符
            console.log('🚨 异常处理，更新AI消息ID:', aiMessageId);
            this.updateMessage(aiMessageId, '');
        } finally {
            this.sending = false;
            this.updateSendButton(false);
            
            // 稍后自动隐藏时间线
            if (this.hideTimeline) {
                setTimeout(() => {
                    this.hideTimeline();
                }, 3000);
            }
        }
    }
    
    sendQuickSuggestion(suggestion) {
        if (this.elements.chatInput) {
            this.elements.chatInput.value = suggestion;
            this.sendMessage();
        }
    }
    
    addMessage(type, content, loading = false) {
        if (!this.elements.chatHistory) return null;
        
        const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        const messageEl = document.createElement('div');
        console.log('🎨 类别:', { type});
        messageEl.className = `message-wrapper ${type}-message-wrapper`;
        messageEl.id = messageId;
        
        console.log('🎨 添加消息:', { type, content, loading, messageId, className: messageEl.className });
        console.log('🔍 消息类型验证:', type === 'user' ? '用户消息' : type === 'ai' ? 'AI消息' : '未知类型');
        
        if (type === 'user') {
            messageEl.innerHTML = `
                <div class="message user-message">
                    <div class="message-content">
                        <div class="message-text">${this.escapeHtml(content)}</div>
                        <div class="message-time">${this.formatTime(new Date())}</div>
                    </div>
                    <div class="message-avatar user-avatar">
                        <i class="fas fa-user"></i>
                    </div>
                </div>
            `;
        } else {
            messageEl.innerHTML = `
                <div class="message ai-message">
                    <div class="message-avatar ai-avatar">
                        <i class="fas fa-robot"></i>
                    </div>
                    <div class="message-content">
                        ${loading ? 
                            `<div class="loading-state">
                                <div class="loading-spinner">
                                    <i class="fas fa-cog fa-spin"></i>
                                </div>
                                <div class="loading-text">伯乐正在思考中...</div>
                            </div>` :
                            `<div class="message-text">${this.renderMarkdown(content)}</div>
                             <div class="message-time">${this.formatTime(new Date())}</div>`
                        }
                    </div>
                </div>
            `;
        }
        
        this.elements.chatHistory.appendChild(messageEl);
        this.scrollToBottom();
        
        return messageId;
    }
    
    updateMessage(messageId, content) {
        console.log('✏️ 更新消息:', { messageId, content });
        const messageEl = document.getElementById(messageId);
        if (messageEl) {
            console.log('📝 找到消息元素:', messageEl.className);
            console.log('🔍 消息元素类型检查:', {
                isUserWrapper: messageEl.classList.contains('user-message-wrapper'),
                isAiWrapper: messageEl.classList.contains('ai-message-wrapper'),
                allClasses: messageEl.className
            });
            const messageContent = messageEl.querySelector('.message-content');
            const loadingState = messageEl.querySelector('.loading-state');
            
            if (messageContent) {
                // Create new content elements
                const textDiv = document.createElement('div');
                textDiv.className = 'message-text';
                // AI消息使用markdown渲染，用户消息使用HTML转义
                const isAiMessage = messageEl.classList.contains('ai-message-wrapper');
                textDiv.innerHTML = isAiMessage ? this.renderMarkdown(content) : this.escapeHtml(content);

                const timeDiv = document.createElement('div');
                timeDiv.className = 'message-time';
                timeDiv.textContent = this.formatTime(new Date());

                if (loadingState) {
                    console.log('🔄 找到loading-state, 准备替换...');
                    messageContent.innerHTML = ''; // Clear the loading state
                    messageContent.appendChild(textDiv);
                    messageContent.appendChild(timeDiv);
                    console.log('✅ loading-state 已被新内容替换');
                } else {
                    console.log('🤔 未找到loading-state, 尝试更新message-text...');
                    const existingText = messageContent.querySelector('.message-text');
                    if(existingText) {
                        // AI消息使用markdown渲染，用户消息使用HTML转义
                        const isAiMessage = messageEl.classList.contains('ai-message-wrapper');
                        existingText.innerHTML = isAiMessage ? this.renderMarkdown(content) : this.escapeHtml(content);
                        console.log('✅ message-text 已更新');
                    } else {
                        messageContent.innerHTML = '';
                        messageContent.appendChild(textDiv);
                        messageContent.appendChild(timeDiv);
                        console.log('✅ message-text 未找到, 已通过 fallback 添加');
                    }
                }
            } else {
                console.error('❌ 未找到 .message-content 元素');
            }
        } else {
            console.error('❌ 未找到消息元素:', messageId);
        }
    }
    
    updateCandidateList(candidates) {
        // 使用统一的显示方法
        this.displayCandidates(candidates);
    }
    
    // 加载所有候选人
    async loadAllCandidates() {
        console.log('📡 开始加载候选人数据...');
        console.log('🔗 API URL:', `${this.apiBaseUrl}/candidates?limit=100`);
        
        try {
            const response = await fetch(`${this.apiBaseUrl}/candidates?limit=100`);
            console.log('📡 API响应状态:', response.status, response.statusText);
            
            if (response.ok) {
                const data = await response.json();
                console.log('📊 API响应数据:', data);
                
                if (data.success && Array.isArray(data.data)) {  // 修复：正确检查数组
                    this.displayCandidates(data.data);
                    console.log(`✅ 已加载 ${data.data.length} 个候选人`);
                } else {
                    console.warn('⚠️ 获取候选人数据失败:', data);
                    console.warn('📊 数据结构检查 - success:', data.success, 'data是否为数组:', Array.isArray(data.data));
                }
            } else {
                console.error('❌ API响应错误:', response.status, response.statusText);
            }
        } catch (error) {
            console.error('❌ 加载候选人失败:', error);
        }
    }
    
    // 显示候选人列表
    displayCandidates(candidates) {
        console.log('📋 displayCandidates 调用，接收到的数据:', candidates);
        console.log('📊 候选人数量:', Array.isArray(candidates) ? candidates.length : '不是数组');
        
        if (!candidates || !Array.isArray(candidates)) {
            console.warn('⚠️ 候选人数据格式错误:', candidates);
            return;
        }
        
        // 保存原始数据用于筛选
        this.allCandidates = candidates;
        this.candidateList = [...candidates]; // 当前显示的候选人
        
        console.log('✅ 候选人数据已保存，原始数据数量:', this.allCandidates.length);
        
        // 隐藏空状态
        if (this.elements.emptyState) {
            this.elements.emptyState.style.display = 'none';
            console.log('✅ 空状态已隐藏');
        } else {
            console.warn('⚠️ 空状态元素未找到');
        }
        
        // 应用当前筛选设置
        console.log('🔄 开始应用筛选...');
        this.applyFilters();
    }
    
    // 应用筛选和排序
    applyFilters() {
        console.log('🔍 applyFilters 开始，原始数据数量:', this.allCandidates?.length);
        
        if (!this.allCandidates || this.allCandidates.length === 0) {
            console.warn('⚠️ applyFilters: 没有原始数据可筛选');
            return;
        }
        
        let filteredCandidates = [...this.allCandidates];
        console.log('📋 初始筛选数据数量:', filteredCandidates.length);
        
        // 状态筛选
        const statusFilter = this.elements.statusFilter?.value || 'all';
        console.log('🏷️ 状态筛选条件:', statusFilter);
        
        if (statusFilter !== 'all') {
            filteredCandidates = filteredCandidates.filter(candidate => {
                const status = candidate.status || 'unknown';
                return status === statusFilter;
            });
            console.log('📊 状态筛选后数量:', filteredCandidates.length);
        }
        
        // 排序
        const sortBy = this.elements.sortSelect?.value || 'match_score';
        console.log('📈 排序方式:', sortBy);
        
        filteredCandidates.sort((a, b) => {
            switch (sortBy) {
                case 'name':
                    return (a.name || '').localeCompare(b.name || '');
                case 'last_updated':
                    return new Date(b.last_updated || 0) - new Date(a.last_updated || 0);
                case 'match_score':
                default:
                    return (b.match_score || 0) - (a.match_score || 0);
            }
        });
        
        this.candidateList = filteredCandidates;
        
        console.log('🎯 开始渲染候选人卡片...');
        this.renderCandidateCards();
        
        console.log(`🔍 筛选结果: ${filteredCandidates.length}/${this.allCandidates.length} 个候选人`);
    }
    
    // 显示所有候选人（重置筛选）
    showAllCandidates() {
        console.log('🔄 开始重置显示所有候选人...');
        
        // 重置筛选条件
        if (this.elements.statusFilter) {
            this.elements.statusFilter.value = 'all';
            console.log('✅ 状态筛选已重置为: all');
        } else {
            console.warn('⚠️ 状态筛选元素未找到');
        }
        
        if (this.elements.sortSelect) {
            this.elements.sortSelect.value = 'match_score';
            console.log('✅ 排序已重置为: match_score');
        } else {
            console.warn('⚠️ 排序选择元素未找到');
        }
        
        // 重新加载所有候选人
        console.log('🔃 重新加载所有候选人数据...');
        this.loadAllCandidates();
        
        console.log('👥 已重置为显示所有候选人');
    }

    renderCandidateCards() {
        console.log('🎨 renderCandidateCards 开始渲染');
        console.log('📊 当前候选人数量:', this.candidateList?.length);
        console.log('🎯 容器元素:', this.elements.candidateList);
        
        if (!this.elements.candidateList) {
            console.error('❌ 候选人列表容器未找到');
            return;
        }
        
        // 清空现有卡片
        const existingCards = this.elements.candidateList.querySelectorAll('.candidate-card');
        console.log('🗑️ 清除现有卡片数量:', existingCards.length);
        existingCards.forEach(card => card.remove());
        
        if (!this.candidateList || this.candidateList.length === 0) {
            console.warn('⚠️ 没有候选人数据可渲染');
            return;
        }
        
        console.log('🔨 开始创建候选人卡片...');
        this.candidateList.forEach((candidate, index) => {
            console.log(`📝 创建第${index + 1}个候选人卡片:`, candidate.name || candidate.id);
            const cardEl = this.createCandidateCard(candidate);
            this.elements.candidateList.appendChild(cardEl);
        });
        
        console.log('✅ 候选人卡片渲染完成');
    }
    
    createCandidateCard(candidate) {
        const cardEl = document.createElement('div');
        cardEl.className = 'candidate-card';
        cardEl.dataset.candidateId = candidate.id;
        
        const skills = candidate.skills || [];
        const displaySkills = skills.slice(0, 3);
        const moreSkillsCount = skills.length - 3;
        
        cardEl.innerHTML = `
            <div class="card-header">
                <div class="candidate-avatar">
                    ${candidate.name ? candidate.name.charAt(0).toUpperCase() : 'N'}
                </div>
                <div class="candidate-info">
                    <h4 class="candidate-name">${this.escapeHtml(candidate.name || '未知姓名')}</h4>
                    ${candidate.position ? `<p class="candidate-title">${this.escapeHtml(candidate.position)}</p>` : ''}
                </div>
                <div class="candidate-status">
                    ${this.renderStatusBadge(candidate.status)}
                </div>
            </div>
            
            <div class="card-content">
                <div class="skills-section">
                    <div class="skills-tags">
                        ${displaySkills.map(skill => `<span class="skill-tag">${this.escapeHtml(skill)}</span>`).join('')}
                        ${moreSkillsCount > 0 ? `<span class="more-skills">+${moreSkillsCount}</span>` : ''}
                    </div>
                </div>
                
                <div class="candidate-meta">
                    <div class="meta-item">
                        <i class="fas fa-briefcase"></i>
                        <span>${candidate.experience_years || 0}年经验</span>
                    </div>
                    ${candidate.location && candidate.location.trim() !== '' ? `
                    <div class="meta-item">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>${this.escapeHtml(candidate.location)}</span>
                    </div>
                    ` : ''}
                </div>
            </div>
        `;
        
        cardEl.addEventListener('click', () => this.selectCandidate(candidate));
        
        return cardEl;
    }
    
    // 渲染状态徽章
    renderStatusBadge(status) {
        const statusMap = {
            'confirmed': { text: '激活', class: 'status-active' },
            'active': { text: '激活', class: 'status-active' },
            'pending': { text: '待定', class: 'status-pending' },
            'rejected': { text: '拒绝', class: 'status-rejected' },
            'unknown': { text: '待评估', class: 'status-unknown' },
            'interview': { text: '面试中', class: 'status-interview' },
            'hired': { text: '已录用', class: 'status-hired' }
        };
        
        const currentStatus = statusMap[status] || statusMap['unknown'];
        return `<span class="status-badge ${currentStatus.class}">${currentStatus.text}</span>`;
    }
    
    selectCandidate(candidate) {
        console.log(`👤 选择候选人: ${candidate.name || candidate.id} (ID: ${candidate.id})`);
        
        this.selectedCandidate = candidate;
        this.currentCandidateId = candidate.id;
        this.currentCandidateName = candidate.name || candidate.id;
        
        // 更新选中状态
        document.querySelectorAll('.candidate-card').forEach(card => {
            card.classList.remove('selected');
        });
        
        const selectedCard = document.querySelector(`[data-candidate-id="${candidate.id}"]`);
        if (selectedCard) {
            selectedCard.classList.add('selected');
        }
        
        // 更新选中状态显示
        const selectedCandidateInfo = document.getElementById('selectedCandidateInfo');
        if (selectedCandidateInfo) {
            selectedCandidateInfo.textContent = `当前选中: ${this.currentCandidateName}`;
        }
        
        this.showCandidateDetails(candidate);
        
        // 加载该候选人的笔记
        this.loadCandidateNotes(candidate.id);
    }
    
    showCandidateDetails(candidate) {
        const noSelection = document.getElementById('noSelection');
        const candidateDetails = document.getElementById('candidateDetails');
        const panelTitle = document.getElementById('panelTitle');
        
        if (noSelection) noSelection.style.display = 'none';
        if (candidateDetails) candidateDetails.style.display = 'block';
        
        if (panelTitle) {
            panelTitle.innerHTML = `
                <i class="fas fa-user-circle"></i>
                ${this.escapeHtml(candidate.name || '未知姓名')}
            `;
        }
        
        this.updateAIAnalysisTab(candidate);
        this.updateResumeTab(candidate);
    }
    
    updateAIAnalysisTab(candidate) {
        const scoreText = document.getElementById('scoreText');
        const prosContent = document.getElementById('prosContent');
        const consContent = document.getElementById('consContent');
        
        // 隐藏分数显示，不在详细视图中显示分数
        if (scoreText) {
            scoreText.style.display = 'none';  // 隐藏分数元素
        }
        
        if (prosContent) {
            prosContent.innerHTML = '<p class="analysis-placeholder">AI分析数据加载中...</p>';
        }
        
        if (consContent) {
            consContent.innerHTML = '<p class="analysis-placeholder">风险分析数据加载中...</p>';
        }
        
        // 添加操作按钮
        this.addAnalysisButtons(candidate);
    }
    
    addAnalysisButtons(candidate) {
        // 查找或创建按钮容器
        let buttonContainer = document.getElementById('analysisButtons');
        if (!buttonContainer) {
            buttonContainer = document.createElement('div');
            buttonContainer.id = 'analysisButtons';
            buttonContainer.className = 'analysis-actions';
            buttonContainer.style.cssText = 'display: flex; gap: 0.8rem; margin-top: 1rem; padding: 1rem;';
            
            // 将按钮容器添加到AI分析标签内容的底部
            const analysisTab = document.getElementById('aiAnalysisContent');
            if (analysisTab) {
                analysisTab.appendChild(buttonContainer);
            }
        }
        
        buttonContainer.innerHTML = `
            <button class="btn btn-primary" onclick="window.livingWorkspace.reanalyzeCandidateClick('${candidate.id}')">
                <i class="fas fa-sync"></i>
                重新分析
            </button>
            <button class="btn btn-secondary" onclick="window.livingWorkspace.generateInterviewClick('${candidate.id}')">
                <i class="fas fa-question-circle"></i>
                生成面试题
            </button>
        `;
    }
    
    // 处理重新分析按钮点击
    async reanalyzeCandidateClick(candidateId) {
        console.log('重新分析候选人:', candidateId);
        
        try {
            this.sending = true;
            
            const message = `请重新分析候选人 ${candidateId} 的详细信息`;
            const response = await this.sendCandidateQuery(message);
            
            if (response.success && response.analyzed_candidates) {
                // 更新候选人列表
                this.updateCandidateList(response.analyzed_candidates);
                
                // 更新当前显示的候选人详情
                const updatedCandidate = response.analyzed_candidates.find(c => c.id === candidateId);
                if (updatedCandidate) {
                    this.showCandidateDetails(updatedCandidate);
                }
            }
            
        } catch (error) {
            console.error('重新分析失败:', error);
            alert('重新分析失败，请稍后重试');
        } finally {
            this.sending = false;
        }
    }
    
    // 处理生成面试题按钮点击
    async generateInterviewClick(candidateId) {
        console.log('生成面试题:', candidateId);
        
        try {
            this.sending = true;
            
            const message = `请为候选人 ${candidateId} 生成个性化面试题`;
            const response = await this.sendCandidateQuery(message);
            
            if (response.success) {
                // 在聊天区域显示面试题 - 使用正确的AI消息添加
                console.log('📝 添加面试题AI消息');
                this.addMessage('ai', response.message || '面试题生成完成');
            }
            
        } catch (error) {
            console.error('生成面试题失败:', error);
            alert('生成面试题失败，请稍后重试');
        } finally {
            this.sending = false;
        }
    }
    
    // 发送候选人相关查询
    async sendCandidateQuery(message) {
        const response = await fetch(`${this.apiBaseUrl}/chat`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message })
        });
        
        return await response.json();
    }
    
    updateResumeTab(candidate) {
        const resumeContent = document.getElementById('resumeContent');
        
        if (resumeContent) {
            const content = candidate.resume_full_text || candidate.content;
            if (content) {
                resumeContent.innerHTML = `
                    <div class="resume-text">
                        ${this.formatResumeContent(content)}
                    </div>
                `;
            } else {
                resumeContent.innerHTML = '<p class="resume-placeholder">简历内容不可用</p>';
            }
        }
    }
    
    switchTab(tabId) {
        if (!tabId) return;
        
        // 更新Tab按钮状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.tab === tabId);
        });
        
        // 更新Tab面板显示
        document.querySelectorAll('.tab-pane').forEach(pane => {
            pane.classList.toggle('active', pane.id === tabId);
        });
    }
    
    toggleTheme() {
        this.isDark = !this.isDark;
        document.documentElement.setAttribute('data-theme', this.isDark ? 'dark' : 'light');
        localStorage.setItem('livingWorkspace_theme', this.isDark ? 'dark' : 'light');
        
        if (this.elements.themeToggle) {
            const icon = this.elements.themeToggle.querySelector('i');
            if (icon) {
                icon.className = this.isDark ? 'fas fa-sun' : 'fas fa-moon';
            }
        }
    }
    
    updateSendButton(loading) {
        if (!this.elements.sendBtn) return;
        
        const icon = this.elements.sendBtn.querySelector('i');
        if (loading) {
            if (icon) icon.className = 'fas fa-cog fa-spin';
            this.elements.sendBtn.disabled = true;
        } else {
            if (icon) icon.className = 'fas fa-paper-plane';
            this.elements.sendBtn.disabled = false;
        }
    }
    
    escapeHtml(text) {
        if (typeof text !== 'string') return String(text);
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    renderMarkdown(text) {
        if (typeof text !== 'string') return String(text);
        
        try {
            // 配置marked选项
            if (typeof marked !== 'undefined') {
                marked.setOptions({
                    breaks: true, // 支持换行
                    gfm: true,    // 支持GitHub Flavored Markdown
                    headerIds: false, // 不生成header id
                    mangle: false     // 不转义email地址
                });
                
                return marked.parse(text);
            } else {
                console.warn('Marked库未加载，回退到HTML转义');
                return this.escapeHtml(text);
            }
        } catch (error) {
            console.error('Markdown渲染错误:', error);
            return this.escapeHtml(text); // 如果渲染失败，回退到HTML转义
        }
    }
    
    formatTime(date) {
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        
        if (diffMins < 1) return '刚刚';
        if (diffMins < 60) return `${diffMins}分钟前`;
        if (diffHours < 24) return `${diffHours}小时前`;
        
        return date.toLocaleDateString('zh-CN');
    }
    
    formatResumeContent(content) {
        return content.replace(/\n/g, '<br>').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
    }
    
    scrollToBottom() {
        if (this.elements.chatHistory) {
            setTimeout(() => {
                this.elements.chatHistory.scrollTop = this.elements.chatHistory.scrollHeight;
            }, 100);
        }
    }
    
    // 调试测试函数
    debugTest() {
        console.log('🔬=== 开始调试测试 ===');
        
        // 清空聊天历史
        if (this.elements.chatHistory) {
            this.elements.chatHistory.innerHTML = '';
            console.log('🧹 聊天历史已清空');
        }
        
        // 测试1: 添加用户消息
        console.log('--- 测试1: 添加用户消息 ---');
        const userMsgId = this.addMessage('user', '测试用户消息');
        console.log('✅ 用户消息已添加:', userMsgId);
        
        // 测试2: 添加AI loading消息
        console.log('--- 测试2: 添加AI loading消息 ---');
        const aiMsgId = this.addMessage('ai', '', true);
        console.log('✅ AI loading消息已添加:', aiMsgId);
        
        // 测试3: 3秒后更新AI消息
        setTimeout(() => {
            console.log('--- 测试3: 更新AI消息内容 ---');
            this.updateMessage(aiMsgId, '这是更新后的AI回复消息，用于测试loading-state是否被正确替换。');
            
            // 检查结果
            setTimeout(() => {
                console.log('--- 🔍 检查测试结果 ---');
                this.checkMessagePositions();
            }, 1000);
        }, 3000);
    }
    
    // 检查消息位置的辅助函数
    checkMessagePositions() {
        if (!this.elements.chatHistory) return;
        
        const messages = this.elements.chatHistory.querySelectorAll('.message-wrapper');
        console.log(`🔍 检查 ${messages.length} 个消息的位置:`);
        
        messages.forEach((msg, index) => {
            const computedStyle = window.getComputedStyle(msg);
            const isUser = msg.classList.contains('user-message-wrapper');
            const isAI = msg.classList.contains('ai-message-wrapper');
            const hasLoadingState = msg.querySelector('.loading-state');
            const hasMessageText = msg.querySelector('.message-text');
            
            console.log(`消息${index + 1}:`, {
                ID: msg.id,
                类型: isUser ? 'user' : isAI ? 'ai' : 'unknown',
                CSS类名: msg.className,
                justifyContent: computedStyle.justifyContent,
                位置: computedStyle.justifyContent === 'flex-end' ? '右边(用户)' : '左边(AI)',
                内容状态: hasLoadingState ? 'loading' : hasMessageText ? 'text' : 'unknown'
            });
        });
    }
    
    // ==================== WebSocket 和时间线相关方法 ====================
    
    initializeWebSocket() {
        if (!window.WebSocket) {
            console.warn('❌ WebSocket不被支持，实时状态功能将被禁用');
            return;
        }
        
        try {
            this.websocket = new WebSocket(this.wsUrl);
            this.setupWebSocketEventHandlers();
            console.log('🔗 WebSocket连接初始化中...', this.wsUrl);
        } catch (error) {
            console.error('❌ WebSocket初始化失败:', error);
        }
    }
    
    setupWebSocketEventHandlers() {
        if (!this.websocket) return;
        
        this.websocket.onopen = () => {
            console.log('✅ WebSocket连接已建立');
            this.reconnectAttempts = 0;
            this.isReconnecting = false;
        };
        
        this.websocket.onmessage = (event) => {
            try {
                const message = JSON.parse(event.data);
                this.handleWebSocketMessage(message);
            } catch (error) {
                console.error('❌ WebSocket消息解析失败:', error);
            }
        };
        
        this.websocket.onclose = (event) => {
            console.log('❌ WebSocket连接已断开:', event.code, event.reason);
            this.handleWebSocketReconnect();
        };
        
        this.websocket.onerror = (error) => {
            console.error('❌ WebSocket连接错误:', error);
        };
    }
    
    handleWebSocketMessage(message) {
        console.log('📨 收到WebSocket消息:', message);
        
        switch (message.type) {
            case 'connection_established':
                console.log('🎉 WebSocket连接确认:', message.data.message);
                break;
                
            case 'status_update':
                this.handleStatusUpdate(message.data);
                break;
                
            case 'heartbeat':
            case 'pong':
                // 心跳包，不需要特别处理
                break;
                
            default:
                console.log('📝 未知WebSocket消息类型:', message.type);
        }
    }
    
    handleWebSocketReconnect() {
        if (this.isReconnecting || this.reconnectAttempts >= this.maxReconnectAttempts) {
            return;
        }
        
        this.isReconnecting = true;
        this.reconnectAttempts++;
        
        const reconnectDelay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
        console.log(`🔄 尝试重连WebSocket (${this.reconnectAttempts}/${this.maxReconnectAttempts})，${reconnectDelay}ms后重试...`);
        
        setTimeout(() => {
            this.initializeWebSocket();
        }, reconnectDelay);
    }
    
    sendWebSocketMessage(message) {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
            this.websocket.send(JSON.stringify(message));
        } else {
            console.warn('⚠️ WebSocket连接未建立，无法发送消息');
        }
    }
    
    // ==================== 时间线管理 ====================
    
    handleStatusUpdate(statusData) {
        console.log('📊 状态更新:', statusData);
        
        // 如果时间线未显示，则显示它
        if (!this.isTimelineVisible()) {
            this.showTimeline();
        }
        
        // 更新时间线状态
        this.updateTimelineStage(statusData);
        
        // 更新进度条
        this.updateTimelineProgress();
    }
    
    showTimeline() {
        if (this.elements.agentStatusTimeline) {
            this.elements.agentStatusTimeline.style.display = 'block';
            this.timelineStages = [];
            this.currentStageIndex = 0;
            
            // 清空之前的时间线内容
            if (this.elements.timelineContent) {
                this.elements.timelineContent.innerHTML = '';
            }
            
            console.log('📈 显示状态时间线');
        }
    }
    
    hideTimeline() {
        if (this.elements.agentStatusTimeline) {
            this.elements.agentStatusTimeline.style.display = 'none';
            this.timelineStages = [];
            this.currentStageIndex = 0;
            console.log('📉 隐藏状态时间线');
        }
    }
    
    isTimelineVisible() {
        return this.elements.agentStatusTimeline && 
               this.elements.agentStatusTimeline.style.display !== 'none';
    }
    
    updateTimelineStage(statusData) {
        const { stage, status, message, timestamp, metadata } = statusData;
        
        // 查找是否已存在该阶段
        let existingStageIndex = this.timelineStages.findIndex(s => s.stage === stage);
        
        if (existingStageIndex === -1) {
            // 添加新阶段
            const newStage = {
                stage,
                status,
                message,
                timestamp,
                metadata: metadata || {},
                element: null
            };
            this.timelineStages.push(newStage);
            existingStageIndex = this.timelineStages.length - 1;
            this.createTimelineStageElement(newStage, existingStageIndex);
        } else {
            // 更新现有阶段
            const existingStage = this.timelineStages[existingStageIndex];
            existingStage.status = status;
            existingStage.message = message;
            existingStage.timestamp = timestamp;
            existingStage.metadata = { ...existingStage.metadata, ...metadata };
            this.updateTimelineStageElement(existingStage);
        }
        
        // 更新当前阶段索引
        if (status === 'thinking' || status === 'executing') {
            this.currentStageIndex = existingStageIndex;
        }
    }
    
    createTimelineStageElement(stageData, index) {
        if (!this.elements.timelineContent) return;
        
        const stageElement = document.createElement('div');
        stageElement.className = 'timeline-item';
        stageElement.setAttribute('data-stage', stageData.stage);
        stageElement.setAttribute('data-index', index);
        
        const stageName = this.getStageDisplayName(stageData.stage);
        const stageIcon = this.getStageIcon(stageData.stage);
        
        stageElement.innerHTML = `
            <div class="timeline-connector"></div>
            <div class="stage-icon ${stageData.status}">
                <i class="fas ${stageIcon}"></i>
            </div>
            <div class="stage-info">
                <div class="stage-name">${stageName}</div>
                <div class="stage-message">${stageData.message}</div>
                <div class="stage-timestamp">${this.formatTimestamp(stageData.timestamp)}</div>
            </div>
        `;
        
        // 添加动画延迟
        setTimeout(() => {
            stageElement.style.animationDelay = `${index * 0.1}s`;
        }, 50);
        
        this.elements.timelineContent.appendChild(stageElement);
        stageData.element = stageElement;
        
        // 自动滚动到最新项目
        setTimeout(() => {
            stageElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }, 200);
    }
    
    updateTimelineStageElement(stageData) {
        if (!stageData.element) return;
        
        const stageIcon = stageData.element.querySelector('.stage-icon');
        const stageMessage = stageData.element.querySelector('.stage-message');
        const stageTimestamp = stageData.element.querySelector('.stage-timestamp');
        
        // 更新图标状态
        if (stageIcon) {
            stageIcon.className = `stage-icon ${stageData.status}`;
        }
        
        // 更新消息
        if (stageMessage) {
            stageMessage.textContent = stageData.message;
        }
        
        // 更新时间戳
        if (stageTimestamp) {
            stageTimestamp.textContent = this.formatTimestamp(stageData.timestamp);
        }
        
        // 更新项目状态类
        stageData.element.className = `timeline-item ${stageData.status}`;
        
        // 如果是活跃状态，添加动画
        if (stageData.status === 'thinking' || stageData.status === 'executing') {
            stageData.element.classList.add('active');
        } else {
            stageData.element.classList.remove('active');
        }
    }
    
    updateTimelineProgress() {
        if (!this.elements.timelineProgress) return;
        
        const completedStages = this.timelineStages.filter(s => s.status === 'completed').length;
        const totalStages = Math.max(this.timelineStages.length, 5); // 假设至少5个阶段
        const progressPercent = (completedStages / totalStages) * 100;
        
        const progressBar = this.elements.timelineProgress.querySelector('.progress-bar');
        if (progressBar) {
            progressBar.style.width = `${Math.min(progressPercent, 100)}%`;
        }
    }
    
    getStageDisplayName(stage) {
        const stageNames = {
            'interaction': '交互处理',
            'orchestrator': '任务调度',
            'candidate_analysis': '候选人分析',
            'candidate_deep_analysis': '深度分析',
            'record_keeping': '记录管理',
            'workbench_ui': '界面更新',
            'tool_executor': '工具执行',
            'completion': '任务完成'
        };
        return stageNames[stage] || stage;
    }
    
    getStageIcon(stage) {
        const stageIcons = {
            'interaction': 'fa-comments',
            'orchestrator': 'fa-cogs',
            'candidate_analysis': 'fa-user-tie',
            'candidate_deep_analysis': 'fa-microscope',
            'record_keeping': 'fa-database',
            'workbench_ui': 'fa-desktop',
            'tool_executor': 'fa-tools',
            'completion': 'fa-check-circle'
        };
        return stageIcons[stage] || 'fa-circle';
    }
    
    formatTimestamp(timestamp) {
        try {
            const date = new Date(timestamp);
            return date.toLocaleTimeString('zh-CN', {
                hour12: false,
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        } catch (error) {
            return timestamp;
        }
    }
    
    // 处理UI指令
    processUICommands(commands) {
        console.log('🎨 处理UI指令:', commands);
        
        commands.forEach(command => {
            switch (command.command) {
                case 'UPDATE_CANDIDATE_LIST':
                    console.log('📋 更新候选人列表:', command.payload);
                    this.updateCandidateList(command.payload);
                    break;
                    
                case 'SHOW_INTERVIEW_QUESTIONS':
                    console.log('❓ 显示面试题:', command.payload);
                    this.showInterviewQuestions(command.payload);
                    break;
                    
                case 'UPDATE_CANDIDATE_STATUS':
                    console.log('🔄 更新候选人状态:', command.payload);
                    this.updateCandidateStatus(command.payload);
                    break;
                    
                case 'SHOW_VISUALIZATIONS':
                    console.log('📊 显示可视化:', command.payload);
                    this.showVisualizations(command.payload);
                    break;
                    
                default:
                    console.log('❓ 未知UI指令:', command);
            }
        });
    }
    
    // 显示面试题
    showInterviewQuestions(interviewData) {
        console.log('📝 显示面试题:', interviewData);
        
        // 创建面试题弹窗
        const modal = document.createElement('div');
        modal.className = 'modal interview-modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>🎯 面试题 - ${interviewData.candidate_name || '候选人'}</h3>
                    <button class="modal-close" onclick="this.closest('.modal').remove()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="interview-info">
                        <p><strong>岗位：</strong>${interviewData.position || '软件工程师'}</p>
                        <p><strong>难度：</strong>${interviewData.difficulty || '中等'}</p>
                        <p><strong>生成时间：</strong>${new Date(interviewData.generated_time || Date.now()).toLocaleString()}</p>
                    </div>
                    <div class="questions-list">
                        ${interviewData.questions.map((q, i) => `
                            <div class="question-item">
                                <h4>问题 ${i + 1}</h4>
                                <p>${q}</p>
                            </div>
                        `).join('')}
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 显示模态框
        setTimeout(() => {
            modal.style.display = 'flex';
        }, 10);
    }
    
    // 更新候选人状态
    updateCandidateStatus(statusData) {
        const candidateCard = document.querySelector(`[data-candidate-id="${statusData.candidate_id}"]`);
        if (candidateCard) {
            const statusElement = candidateCard.querySelector('.status-badge');
            if (statusElement) {
                statusElement.textContent = statusData.status;
                statusElement.style.backgroundColor = statusData.color;
            }
        }
    }
    
    // 显示可视化图表
    showVisualizations(vizData) {
        console.log('📊 显示可视化数据:', vizData);
        // TODO: 实现可视化图表显示
    }
    
    // 笔记相关功能
    initializeNotesFunctionality() {
        // 添加笔记按钮事件监听
        const addNoteBtn = document.getElementById('addNoteBtn');
        const noteInput = document.getElementById('noteInput');
        
        if (addNoteBtn && noteInput) {
            addNoteBtn.addEventListener('click', () => {
                this.addNote();
            });
            
            // 监听Enter键快速添加笔记
            noteInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && e.ctrlKey) {
                    this.addNote();
                }
            });
        }
        
        console.log('📝 笔记功能初始化完成');
    }
    
    async addNote() {
        const noteInput = document.getElementById('noteInput');
        const noteText = noteInput?.value?.trim();
        
        if (!noteText) {
            alert('请输入笔记内容');
            return;
        }
        
        if (!this.currentCandidateId) {
            alert('请先选择一个候选人');
            return;
        }
        
        try {
            console.log(`📝 准备保存笔记给候选人 ${this.currentCandidateId}:`, noteText);
            
            // 显示保存状态
            const addNoteBtn = document.getElementById('addNoteBtn');
            const originalText = addNoteBtn?.textContent;
            if (addNoteBtn) {
                addNoteBtn.disabled = true;
                addNoteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
            }
            
            const response = await fetch(`/api/candidates/${this.currentCandidateId}/notes`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    notes: noteText
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                console.log('✅ 笔记保存成功:', result);
                
                // 清空输入框
                if (noteInput) {
                    noteInput.value = '';
                }
                
                // 显示成功消息
                this.showNotification('笔记保存成功！', 'success');
                
                // 刷新笔记显示
                await this.loadCandidateNotes(this.currentCandidateId);
                
            } else {
                console.error('❌ 笔记保存失败:', result);
                this.showNotification(`笔记保存失败：${result.error}`, 'error');
            }
            
        } catch (error) {
            console.error('❌ 笔记保存出错:', error);
            this.showNotification('笔记保存功能暂时不可用', 'error');
        } finally {
            // 恢复按钮状态
            const addNoteBtn = document.getElementById('addNoteBtn');
            if (addNoteBtn) {
                addNoteBtn.disabled = false;
                addNoteBtn.innerHTML = '<i class="fas fa-plus"></i> 添加笔记';
            }
        }
    }
    
    async loadCandidateNotes(candidateId) {
        if (!candidateId) {
            console.warn('⚠️ 无候选人ID，无法加载笔记');
            return;
        }
        
        try {
            console.log(`📖 加载候选人 ${candidateId} 的笔记`);
            
            const response = await fetch(`/api/candidates/${candidateId}/notes`);
            const result = await response.json();
            
            if (result.success) {
                console.log('✅ 笔记加载成功:', result);
                this.displayCandidateNotes(result.notes, result.updated_at);
            } else {
                console.error('❌ 笔记加载失败:', result);
                this.displayCandidateNotes('', null);
            }
            
        } catch (error) {
            console.error('❌ 笔记加载出错:', error);
            this.displayCandidateNotes('', null);
        }
    }
    
    displayCandidateNotes(notes, updatedAt) {
        // 查找笔记显示区域
        let notesDisplayArea = document.getElementById('notesDisplayArea');
        
        // 如果不存在，创建笔记显示区域
        if (!notesDisplayArea) {
            const interactionsTab = document.getElementById('interactions');
            const notesSection = interactionsTab?.querySelector('.notes-section');
            
            if (notesSection) {
                // 创建笔记显示区域
                const notesDisplayHTML = `
                    <div id="notesDisplayArea" class="notes-display-area">
                        <h4>历史笔记</h4>
                        <div class="notes-content" id="notesContent">
                            ${this.formatNotesDisplay(notes, updatedAt)}
                        </div>
                    </div>
                `;
                notesSection.insertAdjacentHTML('afterend', notesDisplayHTML);
            }
        } else {
            // 更新已存在的笔记显示
            const notesContent = document.getElementById('notesContent');
            if (notesContent) {
                notesContent.innerHTML = this.formatNotesDisplay(notes, updatedAt);
            }
        }
    }
    
    formatNotesDisplay(notes, updatedAt) {
        if (!notes || notes.trim() === '') {
            return '<div class="no-notes">暂无笔记</div>';
        }
        
        // 解析多条笔记（以时间戳格式分隔）
        const notePattern = /\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2})\]\s*([^[]*)/g;
        const notesArray = [];
        let match;
        
        while ((match = notePattern.exec(notes)) !== null) {
            notesArray.push({
                timestamp: match[1],
                content: match[2].trim()
            });
        }
        
        // 如果没有匹配到时间戳格式，作为单条笔记处理
        if (notesArray.length === 0 && notes.trim()) {
            notesArray.push({
                timestamp: updatedAt ? this.formatTimestamp(updatedAt) : '未知时间',
                content: notes.trim()
            });
        }
        
        // 按时间倒序排列（最新的在上面）
        notesArray.reverse();
        
        // 生成HTML
        return notesArray.map(note => `
            <div class="note-item">
                <div class="note-text">${this.escapeHtml(note.content)}</div>
                <div class="note-time">${note.timestamp}</div>
            </div>
        `).join('');
    }
    
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            ${message}
        `;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => notification.classList.add('show'), 100);
        
        // 3秒后自动消失
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }
    
    // 检测并更新笔记
    async checkAndUpdateNotes(userMessage, responseData) {
        try {
            // 检测是否是笔记相关的请求
            const noteKeywords = ['笔记', '添加到笔记', '记录', '备注', '更新笔记'];
            const isNoteRelated = noteKeywords.some(keyword => userMessage.includes(keyword));
            
            // 从响应消息中提取候选人ID
            const candidateIdMatch = userMessage.match(/(\d{8})/);
            
            if (isNoteRelated && candidateIdMatch) {
                const candidateId = candidateIdMatch[1];
                console.log(`🔄 检测到笔记更新请求，候选人ID: ${candidateId}`);
                
                // 等待一小段时间确保后端更新完成
                setTimeout(async () => {
                    await this.refreshCandidateNotes(candidateId);
                }, 1000);
            }
            
            // 如果当前有选中的候选人，并且是笔记相关操作，也刷新当前候选人的笔记
            if (isNoteRelated && this.currentCandidateId) {
                console.log(`🔄 刷新当前选中候选人 ${this.currentCandidateId} 的笔记`);
                setTimeout(async () => {
                    await this.refreshCandidateNotes(this.currentCandidateId);
                }, 1000);
            }
            
        } catch (error) {
            console.error('❌ 检测笔记更新失败:', error);
        }
    }
    
    // 刷新候选人笔记
    async refreshCandidateNotes(candidateId) {
        if (!candidateId) return;
        
        try {
            console.log(`📖 刷新候选人 ${candidateId} 的笔记`);
            await this.loadCandidateNotes(candidateId);
            
            // 显示更新通知
            this.showNotification(`候选人 ${candidateId} 的笔记已更新`, 'success');
            
        } catch (error) {
            console.error(`❌ 刷新候选人 ${candidateId} 笔记失败:`, error);
        }
    }
    
    
    
    // 移除重复的sendMessage方法，使用原始方法并添加时间线功能
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.livingWorkspace = new LivingWorkspace();
    
    // 初始化笔记功能
    setTimeout(() => {
        if (window.livingWorkspace.initializeNotesFunctionality) {
            window.livingWorkspace.initializeNotesFunctionality();
        }
    }, 1000);
});

console.log('🚀 伯乐智能HR Living Workspace 脚本已加载');
console.log('🔬 调试提示: 在控制台输入 livingWorkspace.debugTest() 执行调试测试');